package com.wangzefeng.shop.controller;

import com.wangzefeng.shop.entity.SysUser;
import com.wangzefeng.shop.pojo.CommonResult;
import com.wangzefeng.shop.security.vo.AuthUser;
import com.wangzefeng.shop.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;

/**
 * @Auther: wangzefeng
 * @Date: 2021/3/15 22:26
 * @Description:
 */
@RestController
@RequestMapping("/gateway")
public class AuthController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public CommonResult register(AuthUser user){
        if(user==null) {
            return CommonResult.getErrorResult(500,"发生错误，注册失败！");
        }else if(StringUtils.isEmpty(user.getUsername())){
            return CommonResult.getErrorResult(500,"用户名不能为空，注册失败！");
        }else if(StringUtils.isEmpty(user.getPassword())){
            return CommonResult.getErrorResult(500,"密码不能为空，注册失败！");
        }
        SysUser sysUser = sysUserService.selectOneByUsername(user.getUsername());
        if(sysUser!=null){
            return CommonResult.getErrorResult(500,"用户名已被占用，注册失败！");
        }

        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        user.setUserStatus(1);
        user.setCreateTime(Calendar.getInstance().getTime());
        SysUser newUser = new SysUser();
        BeanUtils.copyProperties(user,newUser);
        /*2021年03月19日 needsign 这里需要给用户添加基础的角色和权限，后期补全*/

        boolean save = sysUserService.save(newUser);
        if(save){
            return CommonResult.getSuccessResult();
        }else{
            return CommonResult.getErrorResult(500,"发生错误，注册失败！");
        }
    }
}
